<?php

namespace app\admin\validate;

use Exception;
use W7\Validate\Validate;

class SystemAuthRule extends Validate
{
    protected $rule = [
        'module'                => 'required',
        'pid'                   => 'required',
        'title'                 => 'required',
        'component'             => 'required|verifyComponet',
        'namespace'             => 'required',
        'path'                  => 'required|verifyPath',
        'method'                => 'required',
        'sort'                  => 'required',
    ];

    protected $message = [
        'module.required'               => '请输入模块名称',
        'pid.required'                  => '请选择父级菜单',
        'title.required'                => '请输入菜单名称',
        'component.required'            => '请选择菜单组件',
        'namespace.required'            => '请输入命名空间',
        'path.required'                 => '请输入权限路由',
        'method.required'               => '请选择请求类型',
        'sort.required'                 => '请输入菜单排序',
    ];

    protected $scene = [
        'add'  => [
            'module',
            'pid',
            'title',
            'component',
            'path',
            'sort',
        ],
        'edit' => [
            'module',
            'pid',
            'title',
            'component',
            'path',
            'sort',
        ],
    ];

    /**
     * 验证路由地址
     * @param mixed $field
     * @param mixed $value
     * @param mixed $parameters
     * @param mixed $validator
     * @throws \Exception
     * @return bool
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function ruleVerifyPath($field, $value, $parameters, $validator)
    {
        if (!strpos($value, '/')) {
            throw new Exception('权限路由格式错误');
        }
        $expl = explode('/', $value);
        $count = count(array_filter($expl));
        if ($count !== 2) {
            throw new Exception('权限路由格式错误!');
        }
        return true;
    }

    /**
     * 根据组件选择数据验证
     * @param mixed $field
     * @param mixed $value
     * @param mixed $parameters
     * @param mixed $validator
     * @throws \Exception
     * @return bool
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function ruleVerifyComponet($field, $value, $parameters, $validator)
    {
        // 远程组件
        if ($value === 'remote/index') {
            $data = $validator->getData();
            if (!isset($data['auth_params']) || !$data['auth_params']) {
                throw new Exception('请输入远程组件参数');
            }
        }
        return true;
    }
}